package com.yvchen.yc_system.module.wx.server.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.errorprone.annotations.Var;
import com.yvchen.yc_system.module.wx.entity.WxMssVo;
import com.yvchen.yc_system.module.wx.server.SendMessageServer;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SendMessageServerImpl implements SendMessageServer {
    /**
     * 模板id
     */
    private String templateId = "FdBFmRrDfMGh_MtEZu0VQlhSUCQTQYKGhZwtnQShcMU";
    /**
     * appid
     */
    private String APPID = "wxd48d2e1700f4cbe7";
    /**
     * appSecret
     */
    private String APPSECRET = "e5977c52d56526d9297e09ae0fdcc032";

    @Resource
    RedisTemplate<String,String> redisTemplate;


    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", APPID); //
        params.put("APPSECRET", APPSECRET); //
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String Access_Token = jsonObject.getString("access_token");
        String expires_in = jsonObject.getString("expires_in");
        System.out.println("有效时长expires_in：" + expires_in);
        return Access_Token;
    }

    public String sendWxMessage(String openId){
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(templateId)
                .build();
        templateMessage.addData(new WxMpTemplateData("time",new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date())));
        templateMessage.addData(new WxMpTemplateData("msg","消息提醒"));
        templateMessage.addData(new WxMpTemplateData("other","其他提醒"));
        System.out.println("格式化消息"+"{ {result.DATA} }\\n\\n领奖金额:{ {withdrawMoney.DATA} }\\n领奖  时间:    { {withdrawTime.DATA} }\\n银行信息:{ {cardInfo.DATA} }\\n到账时间:  { {arrivedTime.DATA} }}");
        try {
            String s = getWxMpService("","").getTemplateMsgService().sendTemplateMsg(templateMessage);
            System.out.println("消息返回"+s);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return "发送成功";
    }

    /**
     * 获取wxApi服务
     * @param appId appid
     * @param secret 秘钥
     * @return
     */
    public WxMpService getWxMpService(String appId,String secret){
        WxMpDefaultConfigImpl wxStorage = new WxMpDefaultConfigImpl();
        wxStorage.setAppId(appId);
        wxStorage.setSecret(secret);
        wxStorage.setToken(getToken(appId,secret));
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        return wxMpService;
    }

    /**
     * 获取token
     * @param appid appid
     * @param secret secret
     * @return
     */
    public String getToken(String appid,String secret){
        String wx_token = redisTemplate.opsForValue().get("WX_TOKEN_"+appid);
        if(StringUtils.isNotEmpty(wx_token)){
            return wx_token;
        }else{
            WxMpDefaultConfigImpl wxStorage = new WxMpDefaultConfigImpl();
            wxStorage.setAppId(appid);
            wxStorage.setSecret(secret);
            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);
            try {
                wx_token= wxMpService.getAccessToken();
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }
            redisTemplate.opsForValue().set("WX_TOKEN",wx_token);
        }
        return wx_token;
    }
}
